//speech_server的测试客户端
//1.进行服务发现 发现speech_server的服务器节点地址信息 并 实例化的通信信道

//3.发起语音识别rpc调用
#include"etcd.hpp"
#include "aip-cpp-sdk/speech.h"
#include"channel.hpp"
#include<gflags/gflags.h>
#include <thread>
#include "speech.pb.h"

DEFINE_bool(run_mode, false, "程序的运行模式, fasle-调试; true-发布;");
DEFINE_string(log_file, "", "发布模式下, 用于指定日志的输出文件");
DEFINE_int32(log_level, 0, "发布模式下, 用于指定日志输出等级");  //trace default 0

DEFINE_string(etcd_host, "http://127.0.0.1:2379", "这是服务中心地址");
DEFINE_string(base_service, "/service", "服务监控根目录");
DEFINE_string(speech_service, "/service/speech_service", "服务监控目录");

void online(const std::string &service_name, const std::string &service_host)
{
    LOG_DEBUG("上线服务, {}-{}", service_name, service_host);
}
void offline(const std::string &service_name, const std::string &service_host)
{
    LOG_DEBUG("下线服务, {}-{}", service_name, service_host);
}
  
int main(int argc, char* argv[])
{
    google::ParseCommandLineFlags(&argc, &argv, true);
    
    xchat::init_logger(FLAGS_run_mode, FLAGS_log_file, FLAGS_log_level);


    //1.先构造Rpc信道管理对象
    auto service_manager = std::make_shared<xchat::ServiceManager>();
    service_manager->declared(FLAGS_speech_service);
    auto put_cb = std::bind(&xchat::ServiceManager::onServiceOnline, service_manager.get(), std::placeholders::_1, std::placeholders::_2);
    auto del_cb = std::bind(&xchat::ServiceManager::onServiceOffline, service_manager.get(), std::placeholders::_1, std::placeholders::_2);
    //2.构造服务发现对象
    xchat::Discovery::ptr dclient = std::make_shared<xchat::Discovery>(FLAGS_etcd_host, FLAGS_base_service, put_cb, del_cb);
    
    
    
    //3.通过Rpc信道管理对象 获取提供Echo服务器的信道
    auto channel = service_manager->choose(FLAGS_speech_service);
    if (!channel)
    {
        std::cout << "获取信道失败" << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
        abort();
    }
    //2.读取语音文件数据
    std::string file_content;
    aip::get_file_content("16k.pcm", &file_content);

    //4.发起EchoRpc调用
    xchat::SpeechService_Stub stub(channel.get());
    xchat::SpeechRecognitionReq req;
    req.set_speech_content(file_content);
    req.set_request_id("123456");

    std::unique_ptr<xchat::SpeechRecognitionRsp> rsp(new xchat::SpeechRecognitionRsp());
    std::unique_ptr<brpc::Controller> cntl(new brpc::Controller());
    stub.SpeechRecognition(cntl.get(), &req, rsp.get(), nullptr); // 同步调用
    if (cntl->Failed())
    {
        std::cout << "rpc 调用失败" << cntl->ErrorText() << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
        abort();
    }
    if(rsp->success() == false)
    {
        std::cout << rsp->errmsg() << std::endl;
    }
    std::cout << "收到响应：" << rsp->request_id() << std::endl;
    std::cout << "收到响应：" << rsp->recognition_result() << std::endl;
    return 0;
}